﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow),num(0)
{
    ui->setupUi(this);
    QMenu *pmenu=ui->menubar->addMenu("文件");
    QAction *pA1=pmenu->addAction(QIcon(":/1.png"),"打开");
    QAction *pA2=pmenu->addAction("另存为");
    QAction *pA3=pmenu->addAction(QIcon(":/2.png"),"退出");
    pA1->setShortcut(QKeySequence(tr("Ctrl+p")));//设置快捷键
    pA2->setShortcut(QKeySequence(tr("Ctrl+s")));
    connect(pA1,&QAction::triggered,this,&MainWindow::on_munuAction_clicked);
    connect(pA2,&QAction::triggered,this,&MainWindow::on_munuAction3_triggered);
    connect(pA3,&QAction::triggered,this,&MainWindow::on_pushButton_clicked);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::paintEvent(QPaintEvent *event)
{
    //qDebug()<<"主窗口被调用:"<<event;
}

void MainWindow::on_pushButton_clicked()
{
    num++;
    ui->lcdNumber->display(num);
}

void MainWindow::on_munuAction_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(
                this,
                tr("Open File"),
                "D:/QT/QTproject/practice_0620/try_2/test.txt",
                tr("Text files (*.txt);;All files (*)")
                );
    if (!fileName.isEmpty())
    {
        qDebug() << "选择的文件是:" << fileName;
        defaultName=fileName;
        QFile file(fileName);//构建qfile对象
        if (file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QTextStream in(&file);
            in.setCodec("UTF-8"); // 设置编码，确保与文件编码一致
            QString fileText = in.readAll();
            file.close();
            ui->textEdit->setText(fileText);
        }
        else
        {
            qDebug() << "打开文件失败";
        }
    }
    else {
        qDebug() << "没有选择文件";
    }
}

void MainWindow::on_munuAction3_triggered()
{
    QString name=QFileDialog::getSaveFileName(
                this,
                tr("另存为"),
                defaultName,
                tr("文本文件(*.txt);;所有文件(*.*)"));
    if(!name.isEmpty())
    {
    qDebug()<<name;
    QFile filename(name);
    if(filename.open(QIODevice::WriteOnly|QIODevice::Text))
    {
    QTextStream out(&filename);
    out.setCodec("UTF-8");
    QString text=ui->textEdit->toPlainText();
    out<<text;
    filename.close();
    }
    else
    {
        qDebug()<<"无法保存";
    }
    }
    else
    {
        qDebug()<<"取消另存为";
    }
}
